﻿using System.Collections.Generic;
using UnityEngine;

namespace UnityX
{
    public class UISystem
    {
        /// <summary>
        /// 当前打开的页面
        /// </summary>
        public static UIPage Current { get; private set; }
        // 所有页面
        private static Dictionary<string, UIPage> uis = new Dictionary<string, UIPage>();
        internal static void Add(UIPage uiObject)
        {
            string name = uiObject.GetType().Name;
            if (uis.ContainsKey(name))
            {
                uis[name] = uiObject;
//#if !UNITY_EDITOR
//                Debug.LogWarning("存在同名界面：" + name);
//#endif
            }
            else
            {
                uis.Add(name, uiObject);
            }
        }
        internal static void Del(UIPage uiObject)
        {
            string name = uiObject.GetType().Name;
            if (uis.ContainsKey(name))
            {
                if (uis[name] == uiObject)
                {
                    uis.Remove(name);
                }
            }
        }
        public static T Get<T>() where T : UIPage
        {
            return (T)Get(typeof(T).Name);
        }
        public static UIPage Get(string name)
        {
            if (uis.ContainsKey(name))
            {
                return uis[name];
            }
            return null;
        }
        public static void Open<T>() where T : UIPage
        {
            Open(typeof(T).Name);
        }
        public static void Open(string name)
        {
            if (uis.ContainsKey(name))
            {
                Current = uis[name];
                Current.UIOpen();
            }
            else
            {
                Debug.LogError("打开界面失败，不存在界面：" + name);
            }
        }
        public static void Close<T>() where T : UIPage
        {
            Close(typeof(T).Name);
        }
        public static void Close(string name)
        {
            if (uis.ContainsKey(name))
            {
                uis[name].UIClose();
            }
            else
            {
                Debug.LogError("关闭界面失败，不存在界面：" + name);
            }
        }
        public static void CloseAll()
        {
            foreach (var item in uis.Values)
            {
                if (item.IsOpen)
                {
                    item.UIClose();
                }
            }
        }
    }
}
